// pages/sportrecord/sportrecord.js
import * as echarts from '../../ec-canvas/echarts';

let time = new Array(); //横坐标
let heartRate = new Array(); //纵坐标

let sportChart;
let sequence_length = 10
let energy = 0
let get_energy_count = 0
const get_energy_count_times = 5
const url = 'https://ericwvi.site/bgmp/api/sport?Action=GetEnergy'

function showHrData(xdata, ydata) {
  //   console.log("xdata+ydata")
  //   console.log(xdata)
  //   console.log(ydata)
  const option = {
    // title: {
    //   // text: '实时心率曲线',
    //   left: 'center',
    //   textStyle: {
    //     color: '#333',
    //     fontWeight: 'bold',
    //     fontSize: 20
    //   },
    // },
    grid: {
      containLabel: true
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      name: '时间',
      //type: 'time',
      boundaryGap: false,
      data: xdata, //x轴上的动态数据
      //show: false
    },
    yAxis: {
      name: '心率/bpm',
      x: 'heartRate',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
      // show: false
    },
    series: [{
      name: '心率数据',
      type: 'line',
      smooth: true,
      data: ydata, //y轴上的动态数据
      lineStyle: {
        normal: {
          width: 1,
          //color: "#FC3159"
        }
      }
    }],
  };
  if (sportChart != undefined && sportChart.setOption != undefined) {
    sportChart.setOption(option)
  } else {
    console.log("sportChart.setOption is undefined")
  }
}

Page({
  data: {
    devices: [
      //   {
      //   'name': 'eee',
      //   'deviceId': 'E4:82:C7:BC:19:6C'
      // }
    ],
    isSearching: '扫描',
    // devices:[],
    deviceCount: 0,
    deviceId: '',
    connected: -1,
    services: [],
    serviceId: '',
    characteristicId: '',
    notify: [],
    hrData: 0,
    energy: 0,
    ec: {
      lazyLoad: true,
    },
  },

  init_echart() {
    // console.log("init echart!!!")
    // 绑定组件
    this.barComponent = this.selectComponent("#mychart-dom-bar");
    // 初始化柱状图
    this.barComponent.init((canvas, width, height, dpr) => {
      // 初始化图表
      sportChart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // 解决模糊显示问题
      })
      return sportChart
    })
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }

    this.init_echart()
    this.setData({
      deviceCount: this.data.devices.length
    })
  },

  getEnergy(heartRate) {
    if (heartRate.length < 10) {
      console.log('too short and return')
      return // energy
    }

    if (get_energy_count < get_energy_count_times) {
      get_energy_count += 1
      console.log("get_energy_count is not enough")
      return
    } else {
      get_energy_count = 0
    }

    var that = this
    wx.request({
      url: url,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      data: {
        "heart_rate": heartRate
      },
      success: (res) => {
        //   console.log("segment sucessfully:", res)
        if (res.data.code === 200) {
          let response_energy = res.data.message.energy
          response_energy = parseFloat(energy) + response_energy / 60 * get_energy_count_times
          energy = response_energy.toFixed(2)
          that.setData({
            energy: energy
          })
          // console.log('energy result is '+energy);
        } else {
          console.log(res.data.message);
        }
      },
      fail: (err) => {
        console.log("segment failed:", err)
      }
    });
    // return energy
  },
  // 给图表加上数据
  refleshData(hr) {
    // var currentDate=new Date().toJSON().substring(0, 10) 
    var currentTime = new Date().toTimeString().substring(0, 8)
    if (time.length >= sequence_length) {
      time.shift(); //如果数据超过了需要解析的最大值，则清除前面的数据，以保留最新的数值
      heartRate.shift();
    }
    time.push(currentTime); //将值保存在队列最后
    heartRate.push(hr);

    this.setData({
      hrData: hr
    })

    this.getEnergy(heartRate)
    //利用 myChart 直接绘制曲线
    showHrData(time, heartRate)
  },
  //   clickme() {
  //       this.init_echart()
  //     let option1 = {
  //         grid: {
  //           containLabel: true
  //         },
  //         tooltip: {
  //           show: true,
  //           trigger: 'axis'
  //         },
  //         xAxis: {
  //           name:'时间',
  //           //type: 'time',
  //           boundaryGap: false,
  //           data: ["14","15","18"], //x轴上的动态数据
  //           //show: false
  //         },
  //         yAxis: {
  //           name:'心率/bpm',
  //           x: 'heartRate',
  //           type: 'value',
  //           splitLine: {
  //             lineStyle: {
  //               type: 'dashed'
  //             }
  //           }
  //           // show: false
  //         },
  //         series: [{
  //           name: '心率数据',
  //           type: 'line',
  //           smooth: true,
  //           data: [1,5,8,6,2], //y轴上的动态数据
  //           lineStyle: {
  //             normal: {
  //                 width: 1,
  //                 //color: "#FC3159"
  //             }
  //           }
  //         }],
  //       };

  //       sportChart.setOption(option1)
  //     console.log("me " + sportChart)
  //   },


  // ArrayBuffer转16进度字符串示例
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('')
  },


  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }

    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])

      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }

    return 0
  },
  getDevice() {
    this.setData({
      isSearching: '扫描中'
    })
    const version = wx.getAppBaseInfo().SDKVersion
    let that = this
    console.log('getDevice')
    if (this.compareVersion(version, '1.1.0') >= 0) {
      that.searchDevice()
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
    this.setData({
      isSearching: '扫描'
    })
  },
  searchDevice() {
    let that = this
    wx.openBluetoothAdapter({ //初始化蓝牙
      success: function (res) {
        console.log(res)
        wx.getBluetoothAdapterState({ //获取本机蓝牙适配器状态。
          success: function (res) {
            console.log(res)
            if (res.available) { //蓝牙适配器是否可用
              wx.startBluetoothDevicesDiscovery({ //搜索附近的蓝牙设备
                services: ['180D'], //筛选过滤搜索的蓝牙设备
                success(res) {
                  //   console.log(res)
                  that.onBluetoothDeviceFound()
                },
                fail(res) {
                  console.log(res)
                }
              })

            } else {
              wx.showModal({
                title: '提示',
                content: '本机蓝牙不可用',
              })
            }
          },
          fail(res) {
            console.log(res)
          }
        })
      },
      fail: function (res) {
        // console.log(res)
        wx.showModal({
          title: '提示',
          content: '蓝牙初始化失败，请打开蓝牙',
        })
      }
    })
  },
  // 第三步 监听发现附近的蓝牙设备
  onBluetoothDeviceFound() {
    // console.log("onBluetoothDeviceFound")
    var that = this
    wx.onBluetoothDeviceFound((res) => {
      console.log(res)
      res.devices.forEach(device => {
        if (!device.name && !devic58e.localName) {
          return
        }
        //   console.log("发现的蓝牙设备", device)
        this.data.devices.push(device)
        that.setData({
          devices: this.data.devices,
          deviceCount: this.data.devices.length
        })
      })
    })
  },
  // 第四步、 建立连接
  connectDevice: function (e) {
    let that = this
    const device = e.currentTarget.dataset.device
    var connectIndex = e.currentTarget.dataset.index
    console.log("connectIndex" + connectIndex)
    console.log("data.connected" + this.data.connected)
    if (this.data.connected != -1) {
      if (connectIndex != this.data.connected) {
        wx.showToast({
          title: '已连接，请先断开与其他设备的连接',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '已连接该设备',
          icon: 'none'
        })
      }
      return
    }

    wx.createBLEConnection({
      deviceId: device.deviceId,
      success: (res) => {
        console.log('createBLEConnection success', res)
        wx.showToast({
          title: '蓝牙连接成功',
          icon: 'none'
        })
        that.stopBluetoothDevicesDiscovery()
        console.log("device(setData):" + device.deviceId)
        that.setData({
          deviceId: device.deviceId,
          connected: connectIndex
        })
        that.getBLEDeviceServices()
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: '蓝牙连接失败',
          icon: 'none'
        })
        //that.stopBluetoothDevicesDiscovery()
      }
    })
  },
  // 第五步、 停止搜索
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log('停止搜索成功');
      },
      fail: function (res) {
        console.log('停止搜索失败');
      }
    });
  },
  //获取设备的服务列表
  getBLEDeviceServices() {
    let that = this
    console.log("getDeviceData" + that.data.deviceId)
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceId,
      success: (getServicesRes) => {
        console.log("获取蓝牙低功耗设备所有服务", getServicesRes);
        that.setData({
          services: getServicesRes.services
        })
        console.log("保存的服务列表", that.data.services)
        that.getBLEDeviceCharacteristics()
      },
      fail: (fail) => {
        console.warn("获取服务信息失败", fail);
      },
      complete: () => {
        wx.hideLoading();
      }
    })

  },
  //获取变化值
  getBLEDeviceCharacteristics() {
    console.log('getBLEDeviceCharacteristics')
    let that = this
    // 我们的设备是第一个服务中有传输数据的服务所以这里选择第一个服务的uuid
    let service = that.data.services[0].uuid
    that.setData({
      serviceId: service
    })
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立链接
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在 wx.getBLEDeviceServices 接口中获取
      serviceId: service,
      success: (ret) => {
        console.log('获取蓝牙低功耗设备某个服务中所有特征', ret)
        let arr = []
        for (var i = 0; i < ret.characteristics.length; i++) {
          console.log('特征值：' + ret.characteristics[i].uuid)
          // 查找所有特征中支持notify功能的特征并保存起来
          if (ret.characteristics[i].properties.notify) {
            console.log("获取开启notify的ServicweId：", service);
            console.log("获取开启notify的CharacteristicsId：", ret.characteristics[i].uuid);
            arr.push({
              service,
              characteristicId: ret.characteristics[i].uuid
            })
          }
        }
        that.setData({
          notify: arr
        })
        console.log('支持notify的服务:', that.data.notify);
        wx.notifyBLECharacteristicValueChange({
          state: true, // 启用 notify 功能
          // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
          deviceId: that.data.deviceId,
          // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
          serviceId: that.data.notify[0].service,
          // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
          characteristicId: that.data.notify[0].characteristicId,
          success: (rest) => {
            console.log('rest' + rest)
            that.readHrData()
          },
          fail: function (fail) {
            console.log(fail.errMsg);
          },
        })
      },
      fail: (fail) => {
        console.warn("获取特征值信息失败", fail);
      },
      complete: (res) => {
        console.log('获取服务信息完成', res);
      }
    })

  },
  readHrData() {
    let that = this
    // 监听特征值变化读取数据
    wx.onBLECharacteristicValueChange((res) => {
      console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
      var heartRate = parseInt(that.ab2hex(res.value), 16) - 1536
      console.log(heartRate)

      // HrData.push({
      //   'hexData':heartRate,
      //   'heartRate':parseInt(heartRate, 16)-1536
      // })
      that.setData({
        hrData: heartRate
      })
      that.refleshData(heartRate)
    })
  },


})